<template>
  <div class="data-filter-container">
    <div class="filter-bar" style="width: 1500px">
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购单号">
              <el-input
                v-model="filterForm.purchaseOrderNumber"
                placeholder="请输入采购单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品编号">
              <el-input
                v-model="filterForm.manufacturerCode"
                placeholder="请输入产品编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input
                v-model="filterForm.productName"
                placeholder="请输入产品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button
              type="primary"
              @click="searchProducts"
              class="filter-button"
              >查询</el-button
            >
            <el-button @click="resetFilter" class="reset-button"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="data-list-bar">
      <span>数据列表</span>
      <el-checkbox-group v-model="selectedRows">
        <div class="button-container">
          <el-button @click="add()" type="primary">新增</el-button>
          <el-button>编辑</el-button>
          <el-button
            type="danger"
            @click="handleDelete('批量删除')"
            :disabled="selectedRows.length === 0"
            >批量删除</el-button
          >
          <el-button @click="handleRefresh">刷新</el-button>
          <el-button @click="handleExport">导出</el-button>
        </div>
      </el-checkbox-group>
    </div>
    <el-table
      :data="dataList"
      border
      class="data-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        label="编号"
        width="155"
        prop="productNewSellModelId"
      ></el-table-column>
      <el-table-column
        label="订单号"
        width="155"
        prop="sellStringCode"
      ></el-table-column>
      <el-table-column
        label="产品名称"
        width="175"
        prop="productName"
      ></el-table-column>
      <el-table-column
        label="产品编号"
        width="175"
        prop="productNum"
      ></el-table-column>
      <el-table-column
        label="产品规格"
        width="155"
        prop="specification"
      ></el-table-column>
      <el-table-column label="单价" width="155" prop="price"></el-table-column>
      <el-table-column
        label="数量"
        width="155"
        prop="quantity"
      ></el-table-column>
      <el-table-column
        label="总额"
        width="155"
        prop="totalPrice"
      ></el-table-column>
      <el-table-column
        label="出库数"
        width="155"
        prop="quantity"
      ></el-table-column>
      <el-table-column
        label="客户编号"
        width="155"
        prop="customerNum"
      ></el-table-column>
      <el-table-column
        label="客户名"
        width="155"
        prop="customerName"
      ></el-table-column>
      <el-table-column
        label="订单总额"
        width="155"
        prop="totalPrice"
      ></el-table-column>
      <el-table-column label="状态" width="155" prop="sellType">
      </el-table-column>

      <el-table-column label="退货" width="155" prop="stute">
        <template #default="scope">
          {{ scope.row.stute ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="155" prop="preparedTime"
        ><template #default="scope">
          {{ formatDate(scope.row.preparedTime) }}
        </template></el-table-column
      >
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click="GetStodto(scope.row.productNum)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="
              handleDelete(scope.row.productNewSellModelId, [
                scope.row.productNum,
              ])
            "
            style="margin-left: 5px"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="upd(scope.row.productNum)"
            style="margin-left: 5px"
            >修改</el-button
          >

          <el-button
            v-if="!scope.row.isReturned"
            type="text"
            size="small"
            @click="GetStodto1(scope.row.productNum)"
            >退货</el-button
          >
          <el-button v-else type="text" size="small" style="margin-left: 5px"
            >已退货</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
    v-model="isDialogVisible"
    title="销售订单明细"
    width="80%"
    :before-close="handleClose"
  >
    <div class="order-info">
      <div class="info-item">
        <span>订单号:</span>
        <span>{{ order.sellStringCode }}</span>
      </div>
      <div class="info-item">
        <span>单据类型:</span>
        <span>{{ order.sellType }}</span>
      </div>
      <div class="info-item">
        <span>关联单号:</span>
        <span>{{ order.productNum }}</span>
      </div>
      <div class="info-item">
        <span>制单人:</span>
        <span>{{ order.preparedBy }}</span>
      </div>
      <div class="info-item">
        <span>制单日期:</span>
        <span>{{ formatDate(order.preparedTime) }}</span>
      </div>
      <div class="info-item">
        <span>发货日期:</span>
        <span>{{ formatDate(order.startTime) }}</span>
      </div>
      <div class="info-item">
        <span>客户编号:</span>
        <span>{{ order.customerNum }}</span>
      </div>
      <div class="info-item">
        <span>客户名称:</span>
        <span>{{ order.customerName }}</span>
      </div>
      <div class="info-item">
        <span>联系人:</span>
        <span>{{ order.contactsName }}</span>
      </div>
      <div class="info-item">
        <span>电话:</span>
        <span>{{ order.phone }}</span>
      </div>
      <div class="info-item">
        <span>备注:</span>
        <span>{{ order.sellDesc }}</span>
      </div>
    </div>
    <el-table :data="order1" border class="product-table">
      <el-table-column label="产品编码" prop="productNum"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <el-table-column label="单位" prop="unitName"></el-table-column>
      <el-table-column label="数量" prop="quantity"></el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="总额" prop="totalPrice"></el-table-column>
    </el-table>
    <div class="button-container">
      <el-button type="primary" @click="confirm">确认</el-button>
      <el-button @click="closeDialog">关闭</el-button>
    </div>
  </el-dialog>
  <el-dialog
    v-model="isDialogVisible1"
    title="退货单"
    width="80%"
    :before-close="handleClose1"
  >
    <div class="order-info">
      <div class="info-item">
        <span>订单号:</span>
        <span>{{ order.sellStringCode }}</span>
      </div>
      <div class="info-item">
        <span>单据类型:</span>
        <span>{{ order.sellType }}</span>
      </div>
      <div class="info-item">
        <span>关联单号:</span>
        <span>{{ order.productNum }}</span>
      </div>
      <div class="info-item">
        <span>制单人:</span>
        <span>{{ order.preparedBy }}</span>
      </div>
      <div class="info-item">
        <span>制单日期:</span>
        <span>{{ formatDate(order.preparedTime) }}</span>
      </div>
      <div class="info-item">
        <span>发货日期:</span>
        <span>{{ formatDate(order.startTime) }}</span>
      </div>
      <div class="info-item">
        <span>客户编号:</span>
        <span>{{ order.customerNum }}</span>
      </div>
      <div class="info-item">
        <span>客户名称:</span>
        <span>{{ order.customerName }}</span>
      </div>
      <div class="info-item">
        <span>联系人:</span>
        <span>{{ order.contactsName }}</span>
      </div>
      <div class="info-item">
        <span>电话:</span>
        <span>{{ order.phone }}</span>
      </div>
      <div class="info-item">
        <span>备注:</span>
        <span>{{ order.sellDesc }}</span>
      </div>
    </div>
    <el-table :data="order1" border class="product-table">
      <el-table-column label="产品编码" prop="productNum"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <el-table-column label="单位" prop="unitName"></el-table-column>
      <el-table-column label="数量" prop="quantity"> </el-table-column>
      <el-table-column label="退货数量">
        <template #default="scope">
          <el-input
            v-model="scope.row.returnQuantity"
            placeholder="输入数量"
            class="table-input"
            @input="calculateTotal(scope.row)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="总额" prop="totalPrice"></el-table-column>
    </el-table>
    <div class="button-container">
      <el-button type="primary" @click="confirm1">确认</el-button>
      <el-button @click="closeDialog">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElTable, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
//...
const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format("YYYY-MM-DD");
};

const router = useRouter();
// 筛选表单数据
const filterForm = reactive({
  manufacturerCode: "",
  purchaseOrderNumber: "",
  productName: "",
  orderStatus: "all",
});

// 数据列表
const dataList = ref([]);
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};
const add = () => {
  router.push("/AddSell");
};
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage;
  searchProducts();
};
onMounted(() => {
  searchProducts();
});
const searchProducts = () => {
  axios
    .get("http://localhost:5128/api/Whouase/GetNewSellModel", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      dataList.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.PageCount;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
// 选中的行
// 修改选择处理逻辑（确保ID有效性）
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 优化后的删除方法
const handleDelete = async (id: any, productNum: any = []) => {
  try {
    let ids = [];
    let stockNumbers = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.productNewSellModelId);
      stockNumbers = selectedRows.value.map((item) => item.productNum);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      stockNumbers = productNum;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "ProductNewSellModel");
    params.append("TableId", "ProductNewSellModelId");
    ids.forEach((id) => params.append("Ids", id.toString()));
    stockNumbers.forEach((num) => params.append("ProductNum", num));

    const res = await axios.delete(
      "https://localhost:7193/api/WHouase/DelsSell",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      searchProducts();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};

// 重置筛选
const resetFilter = () => {
  (filterForm.manufacturerCode = ""),
    (filterForm.purchaseOrderNumber = ""),
    (filterForm.productName = "");
};
const order = ref([]);
const order1 = ref([]);
const isDialogVisible = ref(false);
//明细
const GetStodto = (productNum: string) => {
  isDialogVisible.value = true;
  axios
    .get(
      `http://localhost:5128/api/Whouase/GetNewSellModels?ProductNum=${productNum}`
    )
    .then((res) => {
      order.value = res.data.data[0];
      console.log(order.value);
      // 获取入库单产品信息
      axios
        .get(
          `http://localhost:5128/api/Whouase/GetnewProducts?ProductNum=${productNum}`
        )
        .then((res) => {
          order1.value = res.data.data;
          console.log(order1.value);
        });
    });
};
const confirm = () => {
  // 这里可以添加确认后的逻辑，比如关闭弹窗并进行数据提交等操作
  isDialogVisible.value = false;
};

const closeDialog = () => {
  isDialogVisible.value = false;
};

const handleClose = () => {
  // 关闭弹窗前的逻辑处理
  closeDialog();
};

const isDialogVisible1 = ref(false);
//明细
const GetStodto1 = (productNum: string) => {
  isDialogVisible1.value = true;
  axios
    .get(
      `http://localhost:5128/api/Whouase/GetNewSellModels?ProductNum=${productNum}`
    )
    .then((res) => {
      order.value = res.data.data[0];
      console.log(order.value);
      // 获取入库单产品信息
      axios
        .get(
          `http://localhost:5128/api/Whouase/GetnewProducts?ProductNum=${productNum}`
        )
        .then((res) => {
          order1.value = res.data.data;
          console.log(order1.value);
        });
    });
};
const confirm1 = async () => {
  // 构建请求数据
  const payload = {
    returnGoodsList: order1.value.map((item) => ({
      returnQuantity: Number(item.returnQuantity),
      price: Number(item.price),
      totalPrice: Number(item.totalPrice),
      productNum: item.productNum,
      productName: item.productName,
    })),
  };

  try {
    // 发起POST请求到后端接口
    const res = await axios.post(
      "https://localhost:7193/api/WHouase/AddReturnGoods",
      payload
    );
    if (res.data.code === 200) {
      // 遍历 order1 中的每个商品
      order1.value.forEach((orderItem) => {
        // 在 dataList 中找到对应的行
        const matchingRow = dataList.value.find(
          (row) => row.productNum === orderItem.productNum
        );
        if (matchingRow) {
          // 调用 handleReturn 函数更新状态
          const handleReturn = (row) => {
            try {
              row.stute = true;
              row.isReturned = true;
              ElMessage.success("退货操作成功");
            } catch (error) {
              ElMessage.error("退货操作失败，请检查网络或联系管理员");
              console.error(error);
            }
          };
          handleReturn(matchingRow);
        }
      });
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败，请检查控制台");
    console.error("API Error:", error);
  }
  // 关闭弹窗
  isDialogVisible1.value = false;
};

const closeDialog1 = () => {
  isDialogVisible1.value = false;
};

const handleClose1 = () => {
  // 关闭弹窗前的逻辑处理
  closeDialog1();
};
const calculateTotal = (row: any) => {
  if (row.returnQuantity !== "" && row.price !== "") {
    row.totalPrice = (Number(row.returnQuantity) * Number(row.price)).toFixed(
      2
    );
  } else {
    row.totalPrice = "";
  }
};
//修改
const upd = (productNum: string) => {
  router.push({
    path: "/UpdateSell",
    query: {
      productNum: productNum,
    },
  });
};
</script>

<style scoped>
.data-filter-container {
  padding: 10px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.advanced-search {
  color: #409eff;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.filter-button,
.reset-button,
.refill-button {
  margin-left: 10px;
}

.data-list-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.select-all {
  margin-right: 10px;
}

.data-table {
  width: 100%;
  margin-bottom: 10px;
}

.batch-operation-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
}

.batch-operation-button {
  margin-right: 10px;
}

.pagination {
  text-align: center;
}
</style>
<style scoped>
.order-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}
.info-item {
  width: 300px;
}
.product-table {
  width: 100%;
  margin-bottom: 20px;
}
.button-container {
  text-align: right;
}
</style>